<template>
    <div class="content-wrapper">
        <el-row class="content-row">
            <el-col class="height-init" :span="24">
                <div class="container">
                    <el-row class="handle-box">
                        <el-input v-model="query.userName" placeholder="用户名" class="handle-input mr10"></el-input>
                        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                        <el-button type="primary" v-if="checkAuth(auths.add)" icon="el-icon-plus" @click="addUser">新增</el-button>
                        <el-button type="primary" v-if="checkAuth(auths.update)" icon="el-icon-edit" class="handle-del" @click="handleEdit">编辑</el-button>
                        <el-button type="primary" v-if="checkAuth(auths.delete)" icon="el-icon-delete" class="handle-del" @click="handleDelete">删除</el-button>
                        <el-button type="primary" v-if="checkAuth(auths.reset)" icon="el-icon-setting" class="handle-del" @click="handleSetting">重置密码</el-button>
                    </el-row>
                    <el-row class="list-table-row">
                        <el-table
                                :data="tableData"
                                border
                                class="table"
                                height="100%"
                                ref="multipleTable"
                                header-cell-class-name="table-header"
                                @selection-change="handleSelectionChange"
                        >
                            <el-table-column type="selection" width="55" align="center"></el-table-column>
                            <el-table-column type="index" width="50" align="center" label="序号"></el-table-column>
                            <el-table-column prop="userName" label="用户名" align="center"></el-table-column>
                            <el-table-column prop="name" label="姓名" align="center"></el-table-column>
                            <el-table-column prop="telephone" align="center" label="电话号码" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="status" label="状态" align="center">
                                <template slot-scope="scope" >
                                    <span v-if="scope.row.status == 0">启用</span>
                                    <span v-if="scope.row.status == 1">禁用</span>
                                    <span v-if="scope.row.status == 2">锁住</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="createUser" align="center" label="创建人"></el-table-column>
                            <el-table-column prop="createTime" align="center" label="创建时间" show-overflow-tooltip>
                                <template slot-scope="scope" >
                                    {{renderTime(scope.row.createTime)}}
                                </template>
                            </el-table-column>
                            <el-table-column prop="updateUser" align="center" label="最近修改人">
                                <template slot-scope="scope" >
                                    <span v-if="scope.row.updateUser!==null">{{scope.row.updateUser}}</span>
                                    <span v-if="scope.row.updateUser==null">-</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="updateTime" align="center" label="修改时间" show-overflow-tooltip>
                                <template slot-scope="scope" >
                                    <span v-if="scope.row.updateTime!==null">{{renderTime(scope.row.updateTime)}}</span>
                                    <span v-if="scope.row.updateTime==null">-</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-row>
                    <el-row class="pagination-self">
                        <el-pagination
                                background
                                layout="total, sizes, prev, pager, next"
                                :current-page="query.pageNo"
                                :page-size="query.pageSize"
                                :total="pageTotal"
                                @size-change="handleSizeChange"
                                @current-change="handlePageChange"
                        ></el-pagination>
                    </el-row>
                </div>
            </el-col>
        </el-row>

        <!-- 新增弹出框 -->
        <el-dialog title="新增账户" :visible.sync="addVisible" width="30%" v-loading.fullscreen.lock="fullscreenLoading">
            <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="100px">
                <el-row style="height: 250px">
                    <el-form-item label="账户名称" prop="name">
                        <el-input v-model="addForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="账号" prop="userName">
                        <el-input v-model="addForm.userName"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="addForm.password" type="password"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号码" prop="telephone">
                        <el-input v-model="addForm.telephone"></el-input>
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-radio-group v-model="addForm.status">
                            <el-radio label="0">启用</el-radio>
                            <el-radio label="1">禁用</el-radio>
                            <el-radio label="2">锁定</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="菜单权限" prop="roleId"  >
                        <el-select v-model="addForm.roleId" clearable placeholder="请选择角色">
                            <el-option
                                    v-for="item in roles"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveUser('addForm')">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑账号" :visible.sync="editVisible" width="30%" v-loading.fullscreen.lock="fullscreenLoading">
            <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="80px">
                <el-row style="height: 250px">
                    <el-form-item label="账户名称" prop="name">
                        <el-input v-model="editForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="账号" prop="userName">
                        <el-input v-model="editForm.userName"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="editForm.password" type="password" readonly></el-input>
                    </el-form-item>
                    <el-form-item label="手机号码" prop="telephone">
                        <el-input v-model="editForm.telephone"></el-input>
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-radio-group v-model="editForm.status">
                            <el-radio label="0">启用</el-radio>
                            <el-radio label="1">禁用</el-radio>
                            <el-radio label="2">锁定</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="菜单权限" prop="roleId"  >
                        <el-select v-model="editForm.roleId" clearable placeholder="请选择角色">
                            <el-option
                                    v-for="item in roles"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateUser('editForm')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { allList } from '../../../../api/sys/role'
import { fetchData, saveUser, updateUser, getUserRole, deleteUser, resetPassword } from '../../../../api/sys/user'

export default {
    name: 'userList',
    data() {
        return {
            query: {
                userName: '',
                pageNo: 1,
                pageSize: 20
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            addVisible:false,
            editVisible: false,
            pageTotal: 0,
            fullscreenLoading: false,
            roles:[], //获取所有的菜单
            form: {},
            addForm:{
                status:'0',
                name:'',
                userName:'',
                roleId:'',
                password:'',
                telephone:'',
            },
            editForm: {
                status:'0',
                name:'',
                userName:'',
                roleId:'',
                password:'',
                telephone:'',
            },
            addRules: {
                name: [
                    { required: true, message: '请输入账户名称', trigger: ['blur','change'] }
                ],
                userName:[
                    { required: true, message: '请输入账号', trigger: ['blur','change'] }
                ],
                roleId:[
                    { required: true, message: '请选择菜单权限', trigger: ['blur','change'] }
                ],
                password:[
                    { required: true, pattern:/^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{3,30}$/, message: '请输入密码(包含数字大小写字母特殊字符)', trigger: ['blur','change'] }
                ],
                status:[
                    { required: true, message: '请选择状态', trigger: ['blur','change'] }
                ]
            },
            editRules: {
                name: [
                    { required: true, message: '请输入账户名称', trigger: ['blur','change'] }
                ],
                userName:[
                    { required: true, message: '请输入账号', trigger: ['blur','change'] }
                ],
                roleId:[
                    { required: true, message: '请选择菜单权限', trigger: ['blur','change'] }
                ],
                password:[
                    { required: true, message: '请输入密码', trigger: ['blur','change'] }
                ],
                status:[
                    { required: true, message: '请选择状态', trigger: ['blur','change'] }
                ]
            }
        };
    },
    created() {
        this.getData();
        this.getAllRole();
    },
    props:['auths'],
    methods: {
        //更新密码
        handleSetting(){
            if(this.multipleSelection.length>0){
                let selIds = this.multipleSelection.map((item,index)=>{return item.id});
                // 二次确认删除
                this.$confirm('是否将密码设置为lht@123？', '提示', {
                    type: 'warning'
                }).then(() => {
                    resetPassword({ids:selIds, password:'lht@123'}).then(res => {
                        if (res.code == '0') {
                            this.$message.success('重置密码成功');
                            this.getData();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    });
                }).catch(() => {});
            }else{
                this.$message({
                    message: '请选择记录!',
                    type: 'error'
                });
            }
        },
        //获取所有的角色
        getAllRole(){
            allList().then(res => {
                console.log(res);
                this.roles = res.data;
            });
        },
        /**
         * 获取列表
         */
        getData() {
            fetchData(this.query).then(res => {
                console.log(res);
                this.tableData = res.data.records;
                this.pageTotal = res.data.total || 50;
            });
        },
        /**
         * 弹窗新增用户
         */
        addUser(){
            this.resetForm('addForm');
            this.addVisible = true;
        },
        /**
         * 点击保存用户
         */
        saveUser(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.fullscreenLoading=true;
                    saveUser(this.addForm).then(res => {
                        console.log(res);
                        if (res.code == '0') {
                            this.fullscreenLoading=false;
                            this.addVisible = false;
                            this.$message({
                                message: '新增成功',
                                type: 'success'
                            });
                            this.resetForm('addForm');
                            this.getData();
                        } else {
                            this.fullscreenLoading=false;
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageNo', 1);
            this.getData();
        },

        // 删除操作
        handleDelete() {
            if(this.multipleSelection.length>0){
                let selIds = this.multipleSelection.map((item,index)=>{return item.id});
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    deleteUser({ids:selIds}).then(res => {
                        if (res.code == '0') {
                            this.$message.success('删除成功');
                            this.getData();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    });
                }).catch(() => {});
            }else{
                this.$message({
                    message: '请选择记录!',
                    type: 'error'
                });
            }
        },

        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },

        // 编辑操作
        handleEdit() {
            if(this.multipleSelection.length>0){
                if(this.multipleSelection.length==1){
                    let row = this.multipleSelection[0];
                    Object.assign(this.editForm,row);
                    this.editForm.status = row.status+'';
                    this.editVisible = true;
                    getUserRole({userId:row.id}).then(res=>{
                        console.log(res);
                        if(res.data!==null && res.data.length>0){
                            this.editForm.roleId = res.data[0].roleId;
                        }else{
                            this.editForm.roleId='';
                        }
                    })
                }else{
                    this.$message({
                        message: '只能选择一条记录进行编辑!!',
                        type: 'error'
                    });
                }
            }else{
                this.$message({
                    message: '请选择记录!',
                    type: 'error'
                });
            }
        },

        /**
         * 编辑后保存用户信息
         * @param formName
         */
        updateUser(formName) {
            console.log(this.editForm);
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.fullscreenLoading=true;
                    updateUser(this.editForm).then(res => {
                        console.log(res);
                        if (res.code == '0') {
                            this.fullscreenLoading=false;
                            this.editVisible = false;
                            this.$message({
                                message: '更新成功',
                                type: 'success'
                            });
                            this.resetForm('editForm');
                            this.editForm.roleId='';
                            this.getData();
                        } else {
                            this.fullscreenLoading=false;
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageNo', val);
            this.getData();
        },
        //分页器
        handleSizeChange(val) {
            this.$set(this.query, 'pageSize', val);
            this.getData();
        },
    }
};
</script>

<style scoped>

    .content-wrapper{
        height:100%;
        overflow-y: hidden;
    }

    .content-row{
        height: 100%;
    }

    .height-init{
        height: 100%;
    }

    .container{
        height: 100%;
    }

    .handle-box {
        height: 6.5%;
    }

    .handle-input {
        width: 120px;
        display: inline-block;
    }

    .list-table-row{
        height:83%;
    }

    .table {
        width: 100%;
        height: 100%;
        font-size: 14px;
    }
    .red {
        color: #ff0000;
    }
    .mr10 {
        margin-right: 10px;
    }
    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
    .pagination-self{
        height:10%;
        text-align: right;
        margin-top: 5px;
    }
</style>
